'''

@author: wyndem
@Emil:   wyndem@qq.com
@FileName: autoCard.py
@Time: 2019/2/27 11:26
@Software: PyCharm
@Description: 

'''
import threading
import time

import requests
from apscheduler.schedulers.blocking import BlockingScheduler
from bs4 import BeautifulSoup
from requests.cookies import RequestsCookieJar
from db.mySqlUtil import db as mydb
from db.sqlLiteUtil import Card, User, db, Recording, Version

pre=0

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
cookie_jar = RequestsCookieJar()
cookie_jar.set("ASP.NET_SessionId","ijsqthswu2isjcha3tqsjbah")
cookie_jar.set("UserEmail","191995501%40qq.com")
cookie_jar.set("UserPass","79C74D66D6FAC761BB028162E5208949")
url ='http://www.goofaka.com/User/Card/Sale'

job_defaults = {

    'coalesce':False,

   'max_instances': 3

}

def get_source(url):
    global pre
    r = requests.get(url, headers=headers, cookies=cookie_jar,timeout=5)
    bs = BeautifulSoup(r.text, "html.parser")
    # 当前总数
    try:
        num = int(bs.select_one("ul.pagination").li.span.text)
    except:
        num=0
        pre=0
    if num > pre:
        card = bs.tbody.find_all('tr')
        # 计算需要处理的数据
        process_num = num - pre
        # 判断是否有下一页
        if process_num > 20:
            printCard(card, 20)
            next_page = bs.select_one("ul.pagination").find_all('li')[-2].a['href']
            get_source(url +next_page)

        # 只有一页
        else:
            printCard(card, process_num)

def lite_heartbeat():
   try:
       Version.get()
   except:
       pass



def printCard(card,num):
    global pre
    pre += num
    for c in range(num):
        td = card[c].find_all('td')
        phone = td[-3].text.strip()
        pwd = td[4].text.strip()[2:30]
        # 查询卡密
        clist = Card.select().where(Card.key == pwd , Card.available == True)
        user = User.select().where(User.phone == phone)
        if  clist.count()!=0 and user.count()!=0:
            c=clist[0]
            user=user.get()
            user.integral += int(c.value)
            with db.atomic() as txn:
                user.save()
                c.available = False
                c.save()
                recording = Recording(card=c.key, ac=user.ac, phone=user.phone, type='自动', value=c.value,
                                      createDate=time.strftime("%F-%H:%M:%S"))
                recording.save()


sched = BlockingScheduler(job_defaults=job_defaults)


async def start(app):

    sched.add_job(get_source, 'interval', seconds=20,args=[url])
    sched.add_job(lite_heartbeat, 'interval', hours=1)
    t = threading.Thread(target=sched.start, name='LoopThread')
    t.start()

async def stop(app):
    sched.shutdown(wait=False)


